
var User = require('../proxy').User;
var Notification = require('../proxy').Notification;
var eventproxy = require('eventproxy');
var cache = require('../common/cache');
var renderHelper = require('../common/render_helper');
var NotificationCollect = require('../proxy').NotificationCollect;
var utility = require('utility');
var util = require('util');
var NotificationModel = require('../models').Notification;
var at = require('../common/at');
var NotificationMessage = require('../proxy').NotificationMessage;

var tools = require('../common/tools');
var config = require('../config');
var EventProxy = require('eventproxy');
var validator = require('validator');
var utility = require('utility');
var _ = require('lodash');
var qrcode = require('yaqrcode');
var S = require('string');

exports.index = function (req, res, next) {
  var page = parseInt(req.query.page, 10) || 1;
  page = page > 0 ? page : 1;
  var tab = 'notification';

  var proxy = new eventproxy();
  proxy.fail(next);

  // 取主题
  var query = {};
  if (tab && tab !== 'all') {
    if (tab === 'good') {
      query.good = true;
    } else {
      query.tab = tab;
    }
  }

  var limit = config.list_notification_count;
  var options = { skip: (page - 1) * limit, limit: limit, sort: '-top -last_reply_at'};
  var optionsStr = JSON.stringify(query) + JSON.stringify(options);

  cache.get(optionsStr, proxy.done(function (notifications) {
    if (notifications) {
      return proxy.emit('notifications', notifications);
    }
    Notification.getNotificationsByQuery(query, options, proxy.done('notifications', function (notifications) {
      return notifications;
    }));
  }));
  // END 取主题

  // 取分页数据
  cache.get('pages', proxy.done(function (pages) {
    if (pages) {
      proxy.emit('pages', pages);
    } else {
      Notification.getCountByQuery(query, proxy.done(function (all_notifications_count) {
        var pages = Math.ceil(all_notifications_count / limit);
        cache.set(JSON.stringify(query) + 'pages', pages, 1000 * 60 * 1);
        proxy.emit('pages', pages);
      }));
    }
  }));

  var tabName = renderHelper.tabName(tab);
  proxy.all('notifications', 'pages',
    function (notifications, pages) {
      res.render('notificationmanager/index', {
        notifications: notifications,
        current_page: page,
        list_notification_count: limit,
        pages: pages,
        tabs: config.tabs,
        tab: tab,
        pageTitle: tabName && (tabName + '版块'),
      });
    });
};

exports.create = function (req, res, next) {

  var departments = config.departments;
  var user_roles = config.user_roles;
  res.render('notificationmanager/create', {
    departments: departments,
    user_roles: user_roles
  })

};

exports.userlist = function (req, res, next) {
  var dep_code = validator.trim(req.params.dep_code).toLowerCase();

  User.getUsersByQuery({department_code: dep_code}, {select: 'loginname'}, function (err, _users) {
    if (err) {
      return next(err);
    }
    var users = [];
    _.forEach( _users, function(user, key) {
      users.push( user.loginname );
    });
    res.send({
      success: true,
      users: users
    });
  });
};

exports.messagesIndex = function (req, res, next) {
  var user_id = req.session.user._id;
  var ep = new eventproxy();
  ep.fail(next);

  ep.all('has_read_messages', 'hasnot_read_messages', function (has_read_messages, hasnot_read_messages) {
    res.render('notificationmessage/index', {
      has_read_messages: has_read_messages,
      hasnot_read_messages: hasnot_read_messages
    });
  });

  ep.all('has_read', 'unread', function (has_read, unread) {
    [has_read, unread].forEach(function (msgs, idx) {
      var epfill = new eventproxy();
      epfill.fail(next);
      epfill.after('message_ready', msgs.length, function (docs) {
        docs = docs.filter(function (doc) {
          return !doc.is_invalid;
        });
        ep.emit(idx === 0 ? 'has_read_messages' : 'hasnot_read_messages', docs);
      });
      msgs.forEach(function (doc) {
        NotificationMessage.getMessageById(doc._id, epfill.group('message_ready'));
      });
    });
  });

  NotificationMessage.getReadMessagesByUserId(user_id, ep.done('has_read'));

  NotificationMessage.getUnreadMessageByUserId(user_id, ep.done('unread', function (docs) {
    docs.forEach(function (doc) {
      doc.has_read = true;
      doc.save();
    });
    return docs;
  }));
}
exports.createPost = function (req, res, next) {
  var title = validator.trim(req.body.title);
  title = validator.escape(title);
  var tab = 'notification';
  var content = validator.trim(req.body.content);
  var at_users = req.body.users;
  var dep_users_count = req.body.dep_users_count;
  var dep_code = req.body.department;

  // 验证
  var editError;
  if (title === '') {
    editError = '标题不能是空的。';
  } else if (title.length < 5 || title.length > 100) {
    editError = '标题字数太多或太少。';
  } else if (dep_users_count == 0) {
    editError = '通知的人数为空';
  } else if (content === '') {
    editError = '内容不可为空';
  }
  // END 验证

  if (editError) {
    res.status(422);
    var departments = config.departments;
    var user_roles = config.user_roles;
    res.render('notificationmanager/create', {
      edit_error: editError,
      title: title,
      content: content,
      departments: departments,
      user_roles: user_roles
    });
    return;
  }

  if (at_users === undefined && dep_users_count !== 0) {
    User.getUsersByQuery({department_code: dep_code}, {select: 'loginname'}, function (err, _users) {
      if (err) {
        return next(err);
      }
      var at_users = [];
      _.forEach( _users, function(user, key) {
        at_users.push( user.loginname );
      });

      save_notification(title, content, at_users);
    });
  } else {
    save_notification(title, content, at_users);
  }

  function save_notification(title, content, at_users){
    var at_users_str = at_users.join(" @");
    at_users_str = '@' + at_users_str;
    content = at_users_str + ' <br /> ' + content;

    Notification.newAndSave(title, content, tab, req.session.user._id, function (err, notification) {
      if (err) {
        return next(err);
      }

      var proxy = new EventProxy();

      proxy.all('score_saved', function () {
        res.redirect('/notification/' + notification._id);
      });
      proxy.fail(next);
      User.getUserById(req.session.user._id, proxy.done(function (user) {
        user.score += 5;
        user.notification_count += 1;
        user.save();
        req.session.user = user;
        proxy.emit('score_saved');
      }));

      //发送at消息
      NotificationMessage.sendNotifacationMessageToMentionUsers(content, notification._id, req.session.user._id);
    });
  }
};